<!DOCTYPE html>
<html lang=zh>
<head>
    <!-- so meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5" />
    <meta name="description" content="1.Mybatis简介初识mybatis MyBatis 是一款优秀的持久层框架，它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO（Plain Old Java Objects，普通老式 Java 对象）为数据库中的记录。  什么">
<meta property="og:type" content="article">
<meta property="og:title" content="mybatis">
<meta property="og:url" content="https://mihaoyou.gitee.io/mybatis/index.html">
<meta property="og:site_name" content="Cactus">
<meta property="og:description" content="1.Mybatis简介初识mybatis MyBatis 是一款优秀的持久层框架，它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO（Plain Old Java Objects，普通老式 Java 对象）为数据库中的记录。  什么">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946747.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946833.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946929.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946016.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946094.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946180.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946287.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946386.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946471.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946566.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946682.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946775.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946866.png">
<meta property="og:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946986.png">
<meta property="article:published_time" content="2023-09-05T06:29:22.000Z">
<meta property="article:modified_time" content="2023-09-18T14:11:09.064Z">
<meta property="article:author" content="云雪">
<meta property="article:tag" content="mybatis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946747.png">
    
    
      
        
          <link rel="shortcut icon" href="/images/favicon.ico">
        
      
      
        
          <link rel="icon" type="image/png" href="/images/favicon-192x192.png" sizes="192x192">
        
      
      
        
          <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
        
      
    
    <!-- title -->
    <title>mybatis</title>

    <!-- styles -->
    
<link rel="stylesheet" href="/css/style.css">


     <!-- 添加到这里！！ -->
     
<script src="/js/switch.js"></script>


    <!-- persian styles -->
    
    <!-- rss -->
    
    
	<!-- mathjax -->
	
<meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="Cactus" type="application/atom+xml">
</head>

<body class="max-width mx-auto px3 ltr">
    
      <div id="header-post">
  <a id="menu-icon" href="#" aria-label="目录"><i class="fas fa-bars fa-lg"></i></a>
  <a id="menu-icon-tablet" href="#" aria-label="目录"><i class="fas fa-bars fa-lg"></i></a>
  <a id="top-icon-tablet" href="#" aria-label="顶部" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');" style="display:none;"><i class="fas fa-chevron-up fa-lg"></i></a>
  <span id="menu">
    <span id="nav">
      <ul>
        <!--
       --><li><a href="/">首页</a></li><!--
     --><!--
       --><li><a href="/about/">关于</a></li><!--
     --><!--
       --><li><a href="/archives/">归档</a></li><!--
     --><!--
       --><li><a href="/categories/">分类</a></li><!--
     --><!--
       --><li><a href="/search/">搜索</a></li><!--
     -->
      </ul>
    </span>
    <br/>
    <span id="actions">
      <ul>
        
        <li><a class="icon" aria-label="上一篇" href="/%E7%B3%BB%E7%BB%9F%E6%9E%B6%E6%9E%84%E5%B8%88/"><i class="fas fa-chevron-left" aria-hidden="true" onmouseover="$('#i-prev').toggle();" onmouseout="$('#i-prev').toggle();"></i></a></li>
        
        
        <li><a class="icon" aria-label="下一篇" href="/css/"><i class="fas fa-chevron-right" aria-hidden="true" onmouseover="$('#i-next').toggle();" onmouseout="$('#i-next').toggle();"></i></a></li>
        
        <li><a class="icon" aria-label="返回顶部" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up" aria-hidden="true" onmouseover="$('#i-top').toggle();" onmouseout="$('#i-top').toggle();"></i></a></li>
        <li><a class="icon" aria-label="分享文章" href="#"><i class="fas fa-share-alt" aria-hidden="true" onmouseover="$('#i-share').toggle();" onmouseout="$('#i-share').toggle();" onclick="$('#share').toggle();return false;"></i></a></li>

        <li><a class="icon" aria-label="切换主题 " href="#"><i class="fas fa-lightbulb" aria-hidden="true" onmouseover="$('#i-switch').toggle();" onmouseout="$('#i-switch').toggle();" onclick="switchNightMode();return false";></i></a></li>

      </ul>
      <span id="i-prev" class="info" style="display:none;">上一篇</span>
      <span id="i-next" class="info" style="display:none;">下一篇</span>
      <span id="i-top" class="info" style="display:none;">返回顶部</span>
      <span id="i-share" class="info" style="display:none;">分享文章</span>
      <span id="i-switch" class="info" style="display:none;">切换主题</span>
    </span>
    <br/>
    <div id="share" style="display: none">
      <ul>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://mihaoyou.gitee.io/mybatis/"><i class="fab fa-facebook " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://mihaoyou.gitee.io/mybatis/&text=mybatis"><i class="fab fa-twitter " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://mihaoyou.gitee.io/mybatis/&title=mybatis"><i class="fab fa-linkedin " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://mihaoyou.gitee.io/mybatis/&is_video=false&description=mybatis"><i class="fab fa-pinterest " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=mybatis&body=Check out this article: https://mihaoyou.gitee.io/mybatis/"><i class="fas fa-envelope " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://mihaoyou.gitee.io/mybatis/&title=mybatis"><i class="fab fa-get-pocket " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://mihaoyou.gitee.io/mybatis/&title=mybatis"><i class="fab fa-reddit " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://mihaoyou.gitee.io/mybatis/&title=mybatis"><i class="fab fa-stumbleupon " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://mihaoyou.gitee.io/mybatis/&title=mybatis"><i class="fab fa-digg " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://mihaoyou.gitee.io/mybatis/&name=mybatis&description="><i class="fab fa-tumblr " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://mihaoyou.gitee.io/mybatis/&t=mybatis"><i class="fab fa-hacker-news " aria-hidden="true"></i></a></li>
</ul>

    </div>
    <div id="toc">
      <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-Mybatis%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">1.Mybatis简介</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9D%E8%AF%86mybatis"><span class="toc-number">1.1.</span> <span class="toc-text">初识mybatis</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E6%8C%81%E4%B9%85%E5%B1%82%EF%BC%9F"><span class="toc-number">1.2.</span> <span class="toc-text">什么是持久层？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8"><span class="toc-number">2.</span> <span class="toc-text">2.快速入门</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-1-%E5%AE%89%E8%A3%85mybatis%EF%BC%88%E9%85%8D%E7%BD%AE%E4%BA%8Epom-xml%E4%B8%8B%EF%BC%89"><span class="toc-number">2.1.</span> <span class="toc-text">2.1.安装mybatis（配置于pom.xml下）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-2-%E9%85%8D%E7%BD%AE%E6%A0%B8%E5%BF%83%E6%96%87%E4%BB%B6%EF%BC%88mybatis-config-xml%E6%94%BE%E7%BD%AEresource%E7%9B%AE%E5%BD%95%E4%B8%8B%EF%BC%89"><span class="toc-number">2.2.</span> <span class="toc-text">2.2.配置核心文件（mybatis-config.xml放置resource目录下）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-3-%E5%88%9B%E5%BB%BA%E5%B7%A5%E5%85%B7%E7%B1%BB%EF%BC%88%E5%88%9B%E5%BB%BA%E4%BA%8Eutils%E5%8C%85%E4%B8%8B%EF%BC%89"><span class="toc-number">2.3.</span> <span class="toc-text">2.3.创建工具类（创建于utils包下）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4-%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BD%93%E7%B1%BB%EF%BC%88%E5%9C%A8entities%E4%B8%8B%EF%BC%89"><span class="toc-number">2.4.</span> <span class="toc-text">2.4.创建实体类（在entities下）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-5-%E5%88%9B%E5%BB%BA%E6%8E%A5%E5%8F%A3%EF%BC%88%E5%9C%A8dao%E6%88%96%E8%80%85mapper%E5%B1%82%E4%B8%8B%EF%BC%89"><span class="toc-number">2.5.</span> <span class="toc-text">2.5.创建接口（在dao或者mapper层下）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-6-%E9%85%8D%E7%BD%AEStudentMapper-xml%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-number">2.6.</span> <span class="toc-text">2.6.配置StudentMapper.xml配置文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-7-%E7%BC%96%E5%86%99%E6%B5%8B%E8%AF%95%E7%B1%BB"><span class="toc-number">2.7.</span> <span class="toc-text">2.7.编写测试类</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E9%85%8D%E7%BD%AE%E8%A7%A3%E6%9E%90"><span class="toc-number">3.</span> <span class="toc-text">3.配置解析</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#3-1%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE%EF%BC%88environments%EF%BC%89"><span class="toc-number">3.1.</span> <span class="toc-text">3.1环境配置（environments）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-2-%E5%B1%9E%E6%80%A7%EF%BC%88properties%EF%BC%89"><span class="toc-number">3.2.</span> <span class="toc-text">3.2 属性（properties）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3%E7%B1%BB%E5%9E%8B%E5%88%AB%E5%90%8D%EF%BC%88typeAliases%EF%BC%89"><span class="toc-number">3.3.</span> <span class="toc-text">3.3类型别名（typeAliases）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-4%E8%AE%BE%E7%BD%AE"><span class="toc-number">3.4.</span> <span class="toc-text">3.4设置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-5-%E5%85%B6%E4%BB%96%E9%85%8D%E7%BD%AE"><span class="toc-number">3.5.</span> <span class="toc-text">3.5 其他配置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-6-%E6%98%A0%E5%B0%84%E5%99%A8%EF%BC%88mappers%EF%BC%89"><span class="toc-number">3.6.</span> <span class="toc-text">3.6 映射器（mappers）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-7-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%92%8C%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-number">3.7.</span> <span class="toc-text">3.7 生命周期和作用域</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E8%A7%A3%E5%86%B3%E5%B1%9E%E6%80%A7%E5%90%8D%E5%92%8C%E5%AD%97%E6%AE%B5%E5%90%8D%E4%B8%8D%E4%B8%80%E8%87%B4%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">4.</span> <span class="toc-text">4、解决属性名和字段名不一致的问题</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#4-1-%E9%97%AE%E9%A2%98"><span class="toc-number">4.1.</span> <span class="toc-text">4.1 问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-resultMap"><span class="toc-number">4.2.</span> <span class="toc-text">4.2 resultMap</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81%E6%97%A5%E5%BF%97%EF%BC%882020-10-24%EF%BC%89"><span class="toc-number">5.</span> <span class="toc-text">5、日志（2020-10-24）</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#5-1-%E6%97%A5%E5%BF%97%E5%B7%A5%E5%8E%82"><span class="toc-number">5.1.</span> <span class="toc-text">5.1 日志工厂</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-2-Log4j"><span class="toc-number">5.2.</span> <span class="toc-text">6.2 Log4j</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6%E3%80%81%E5%88%86%E9%A1%B5"><span class="toc-number">6.</span> <span class="toc-text">6、分页</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#6-1-%E4%BD%BF%E7%94%A8Limit%E5%88%86%E9%A1%B5"><span class="toc-number">6.1.</span> <span class="toc-text">6.1 使用Limit分页</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-2-RowBounds%E5%88%86%E9%A1%B5"><span class="toc-number">6.2.</span> <span class="toc-text">6.2 RowBounds分页</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-3-%E5%88%86%E9%A1%B5%E6%8F%92%E4%BB%B6"><span class="toc-number">6.3.</span> <span class="toc-text">6.3 分页插件</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7%E3%80%81%E4%BD%BF%E7%94%A8%E6%B3%A8%E8%A7%A3%E5%BC%80%E5%8F%91"><span class="toc-number">7.</span> <span class="toc-text">7、使用注解开发</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#7-1-%E9%9D%A2%E5%90%91%E6%8E%A5%E5%8F%A3%E7%BC%96%E7%A8%8B"><span class="toc-number">7.1.</span> <span class="toc-text">7.1 面向接口编程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#7-2-%E4%BD%BF%E7%94%A8%E6%B3%A8%E8%A7%A3%E5%BC%80%E5%8F%91"><span class="toc-number">7.2.</span> <span class="toc-text">7.2 使用注解开发</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#7-3-CRUD"><span class="toc-number">7.3.</span> <span class="toc-text">7.3 CRUD</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8%E3%80%81Lombok%EF%BC%88%E5%81%B7%E6%87%92%E7%9A%84%E8%AF%9D%E5%8F%AF%E4%BB%A5%E4%BD%BF%E7%94%A8%EF%BC%89"><span class="toc-number">8.</span> <span class="toc-text">8、Lombok（偷懒的话可以使用）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9%E3%80%81%E5%A4%9A%E5%AF%B9%E4%B8%80%E5%A4%84%E7%90%86"><span class="toc-number">9.</span> <span class="toc-text">9、多对一处理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#9-1%E6%B5%8B%E8%AF%95%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA"><span class="toc-number">9.1.</span> <span class="toc-text">9.1测试环境搭建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#9-2-%E6%8C%89%E7%85%A7%E7%BB%93%E6%9E%9C%E5%B5%8C%E5%A5%97%E5%A4%84%E7%90%86"><span class="toc-number">9.2.</span> <span class="toc-text">9.2 按照结果嵌套处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#9-3%E6%8C%89%E7%85%A7%E6%9F%A5%E8%AF%A2%E5%B5%8C%E5%A5%97%E5%A4%84%E7%90%86"><span class="toc-number">9.3.</span> <span class="toc-text">9.3按照查询嵌套处理</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#10-%E3%80%81%E4%B8%80%E5%AF%B9%E5%A4%9A%E5%A4%84%E7%90%86"><span class="toc-number">10.</span> <span class="toc-text">10 、一对多处理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#10-1-%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA"><span class="toc-number">10.1.</span> <span class="toc-text">10.1 环境搭建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#10-2%E6%8C%89%E7%85%A7%E7%BB%93%E6%9E%9C%E5%B5%8C%E5%A5%97%E5%A4%84%E7%90%86"><span class="toc-number">10.2.</span> <span class="toc-text">10.2按照结果嵌套处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#10-3%E6%8C%89%E7%85%A7%E6%9F%A5%E8%AF%A2%E5%B5%8C%E5%A5%97%E5%A4%84%E7%90%86"><span class="toc-number">10.3.</span> <span class="toc-text">10.3按照查询嵌套处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#10-4%E5%B0%8F%E7%BB%93"><span class="toc-number">10.4.</span> <span class="toc-text">10.4小结</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#11%E3%80%81%E5%8A%A8%E6%80%81SQL"><span class="toc-number">11.</span> <span class="toc-text">11、动态SQL</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#11-1%E6%90%AD%E5%BB%BA%E7%8E%AF%E5%A2%83"><span class="toc-number">11.1.</span> <span class="toc-text">11.1搭建环境</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#IF"><span class="toc-number">12.</span> <span class="toc-text">IF</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#choose-when-otherwise"><span class="toc-number">12.1.</span> <span class="toc-text">choose (when, otherwise)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#trim-where-set"><span class="toc-number">12.2.</span> <span class="toc-text">trim (where, set)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Foreach"><span class="toc-number">12.3.</span> <span class="toc-text">Foreach</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#SQL%E7%89%87%E6%AE%B5"><span class="toc-number">12.4.</span> <span class="toc-text">SQL片段</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#12%E3%80%81%E7%BC%93%E5%AD%98%EF%BC%88%E4%BA%86%E8%A7%A3%E5%8D%B3%E5%8F%AF%EF%BC%89"><span class="toc-number">13.</span> <span class="toc-text">12、缓存（了解即可）</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#12-1-%E7%AE%80%E4%BB%8B"><span class="toc-number">13.1.</span> <span class="toc-text">12.1 简介</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AF%E7%BC%93%E5%AD%98-Cache-%EF%BC%9F"><span class="toc-number">13.1.1.</span> <span class="toc-text">1. 什么是缓存[Cache]？</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BD%BF%E7%94%A8%E7%BC%93%E5%AD%98%EF%BC%9F"><span class="toc-number">13.1.2.</span> <span class="toc-text">2. 为什么使用缓存？</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-%E4%BB%80%E4%B9%88%E6%A0%B7%E7%9A%84%E6%95%B0%E6%8D%AE%E8%83%BD%E4%BD%BF%E7%94%A8%E7%BC%93%E5%AD%98%EF%BC%9F"><span class="toc-number">13.1.3.</span> <span class="toc-text">3. 什么样的数据能使用缓存？</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#12-2-Mybatis%E7%BC%93%E5%AD%98"><span class="toc-number">13.2.</span> <span class="toc-text">12.2 Mybatis缓存</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#12-3-%E4%B8%80%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="toc-number">13.3.</span> <span class="toc-text">12.3 一级缓存</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#13-4-%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="toc-number">14.</span> <span class="toc-text">13.4 二级缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#12-5-%E7%BC%93%E5%AD%98%E5%8E%9F%E7%90%86"><span class="toc-number">14.1.</span> <span class="toc-text">12.5 缓存原理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#12-6-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BC%93%E5%AD%98-ehcache%EF%BC%88%E5%8F%AF%E4%BB%A5%E4%BA%86%E8%A7%A3%EF%BC%89"><span class="toc-number">14.2.</span> <span class="toc-text">12.6 自定义缓存-ehcache（可以了解）</span></a></li></ol></li></ol>
    </div>
  </span>
</div>

    
    <div class="content index py4">
        
        <article class="post" itemscope itemtype="http://schema.org/BlogPosting">
  <header>
    
    <h1 class="posttitle" itemprop="name headline">
        mybatis
    </h1>



    <div class="meta">
      <span class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
        <span itemprop="name">云雪</span>
      </span>
      
    <div class="postdate">
      
        <time datetime="2023-09-05T06:29:22.000Z" itemprop="datePublished">2023-09-05</time>
        
      
    </div>


      
    <div class="article-category">
        <i class="fas fa-archive"></i>
        <a class="category-link" href="/categories/java/">java</a>
    </div>


      
    <div class="article-tag">
        <i class="fas fa-tag"></i>
        <a class="tag-link-link" href="/tags/mybatis/" rel="tag">mybatis</a>
    </div>


    </div>
  </header>
  

  <div class="content" itemprop="articleBody">
    <h3 id="1-Mybatis简介"><a href="#1-Mybatis简介" class="headerlink" title="1.Mybatis简介"></a>1.Mybatis简介</h3><h4 id="初识mybatis"><a href="#初识mybatis" class="headerlink" title="初识mybatis"></a>初识mybatis</h4><blockquote>
<p>MyBatis 是一款优秀的持久层框架，它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO（Plain Old Java Objects，普通老式 Java 对象）为数据库中的记录。</p>
</blockquote>
<h4 id="什么是持久层？"><a href="#什么是持久层？" class="headerlink" title="什么是持久层？"></a>什么是持久层？</h4><blockquote>
<p>分层结构是软件设计中一种重要的思想。持久层就是在软件的三层体系结构的基础上发展起来的，它以解决对象和关系这两大领域之间存在的问题为目标，为对象-关系数据库之间提供了一个成功的映射解决方案。</p>
<ul>
<li><em>持久层对象</em>：</li>
<li>由于<strong>内存是易失性存储器</strong>，其中的数据掉电后就会丢失，但一些重要的数据需要长久保存以供使用，显然，仅依靠内存无法实现数据的长期保存。为解决该问题，在计算机领域引入了持久化概念。</li>
<li>持久化（Persisent）指的是将内存中的数据保存到磁盘等存储设备中。</li>
<li><em>经典体系结构</em> <ul>
<li>经典的软件应用体系结构有三层、表示层、业务逻辑层、和数据库层。</li>
<li><strong>表示层：</strong>提供了与用户交互的接口。实现用户操作界面，展示用户需要的数据。</li>
<li><strong>业务逻辑层：</strong>完成业务流程，处理表示层提交的数据请求，并将要保存的数据提交给数据库。</li>
<li><strong>数据库层：</strong>存储需要持久化的业务数据。数据库独立于应用，它提供了系统状态的一种持久化表现形式。</li>
</ul>
</li>
<li><em>对象-关系映射（Obejct&#x2F;Relation Mapping,简称ORM）</em><ul>
<li>实现了Java应用中的对象到关系数据库中表的自动化持久化，并使用元数据来描述对象和数据库之间的映射关系。</li>
<li>元数据通常采用XML格式</li>
</ul>
</li>
</ul>
</blockquote>
<h3 id="2-快速入门"><a href="#2-快速入门" class="headerlink" title="2.快速入门"></a>2.快速入门</h3><h4 id="2-1-安装mybatis（配置于pom-xml下）"><a href="#2-1-安装mybatis（配置于pom-xml下）" class="headerlink" title="2.1.安装mybatis（配置于pom.xml下）"></a>2.1.安装mybatis（配置于pom.xml下）</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies--</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--mysql driver--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.47<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--mybatis 核心--&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.mybatis<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.5.6<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--junit--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.12<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="2-2-配置核心文件（mybatis-config-xml放置resource目录下）"><a href="#2-2-配置核心文件（mybatis-config-xml放置resource目录下）" class="headerlink" title="2.2.配置核心文件（mybatis-config.xml放置resource目录下）"></a>2.2.配置核心文件（mybatis-config.xml放置resource目录下）</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">configuration</span></span></span><br><span class="line"><span class="meta">        <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Config 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">        <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--configuration core file--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">environments</span> <span class="attr">default</span>=<span class="string">&quot;development&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">environment</span> <span class="attr">id</span>=<span class="string">&quot;development&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">transactionManager</span> <span class="attr">type</span>=<span class="string">&quot;JDBC&quot;</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">dataSource</span> <span class="attr">type</span>=<span class="string">&quot;POOLED&quot;</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;driver&quot;</span> <span class="attr">value</span>=<span class="string">&quot;com.mysql.jdbc.Driver&quot;</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;url&quot;</span> <span class="attr">value</span>=<span class="string">&quot;jdbc:mysql://localhost:3306/mybatis?					useSSL=false<span class="symbol">&amp;amp;</span>useUnicode=true<span class="symbol">&amp;amp;</span>characterEncoding=UTF-8&amp;allowPublicKeyRetrieval=true&quot;</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span> <span class="attr">value</span>=<span class="string">&quot;root&quot;</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span> <span class="attr">value</span>=<span class="string">&quot;123456&quot;</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">dataSource</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">environment</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">environments</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--a Mapper.xml need regist in Mybatis core configuration file--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mappers</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">mapper</span> <span class="attr">resource</span>=<span class="string">&quot;com/kuang/dao/UserMapper.xml&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">mappers</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="2-3-创建工具类（创建于utils包下）"><a href="#2-3-创建工具类（创建于utils包下）" class="headerlink" title="2.3.创建工具类（创建于utils包下）"></a>2.3.创建工具类（创建于utils包下）</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//SqlSessionFactory --&gt;SqlSession</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MybatisUtils</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> SqlSessionFactory sqlSessionFactory;</span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//使用Mybaties第一步：获取sqlSessionFactory对象</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">resource</span> <span class="operator">=</span> <span class="string">&quot;mybatis-config.xml&quot;</span>;</span><br><span class="line">            <span class="type">InputStream</span> <span class="variable">inputStream</span> <span class="operator">=</span> Resources.getResourceAsStream(resource);</span><br><span class="line">            sqlSessionFactory = <span class="keyword">new</span> <span class="title class_">SqlSessionFactoryBuilder</span>().build(inputStream);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//既然有了 SqlSessionFactory，顾名思义，我们可以从中获得 SqlSession 的实例。</span></span><br><span class="line">    <span class="comment">// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> SqlSession <span class="title function_">getSqlSession</span><span class="params">()</span>&#123;</span><br><span class="line">	<span class="comment">/* SqlSession sqlSession =  sqlSessionFactory.openSession();</span></span><br><span class="line"><span class="comment">        return sqlSession;</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">        <span class="keyword">return</span> sqlSessionFactory.openSession();</span><br><span class="line">    &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-4-创建实体类（在entities下）"><a href="#2-4-创建实体类（在entities下）" class="headerlink" title="2.4.创建实体类（在entities下）"></a>2.4.创建实体类（在entities下）</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mihayo.entities;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ClassName: Student</span></span><br><span class="line"><span class="comment"> * Package: com.mihayo.entities</span></span><br><span class="line"><span class="comment"> * Description:</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: 余泽云</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Create</span>: 2023/9/4 - 10:38</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: v1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Student</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> Integer sId;</span><br><span class="line">    <span class="keyword">private</span> String sName;</span><br><span class="line">    <span class="keyword">private</span> String sSex;</span><br><span class="line">    <span class="keyword">private</span> Integer tId;</span><br><span class="line">    <span class="keyword">private</span> Teacher teacher;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Student</span><span class="params">()</span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Student</span><span class="params">(Integer sId, String sName, String sSex, Integer tId, Teacher teacher)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.sId = sId;</span><br><span class="line">        <span class="built_in">this</span>.sName = sName;</span><br><span class="line">        <span class="built_in">this</span>.sSex = sSex;</span><br><span class="line">        <span class="built_in">this</span>.tId = tId;</span><br><span class="line">        <span class="built_in">this</span>.teacher = teacher;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Integer <span class="title function_">getsId</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> sId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setsId</span><span class="params">(Integer sId)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.sId = sId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getsName</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> sName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setsName</span><span class="params">(String sName)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.sName = sName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getsSex</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> sSex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setsSex</span><span class="params">(String sSex)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.sSex = sSex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Integer <span class="title function_">gettId</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> tId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">settId</span><span class="params">(Integer tId)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.tId = tId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Teacher <span class="title function_">getTeacher</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> teacher;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setTeacher</span><span class="params">(Teacher teacher)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.teacher = teacher;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Student&#123;&quot;</span> +</span><br><span class="line">                <span class="string">&quot;sId=&quot;</span> + sId +</span><br><span class="line">                <span class="string">&quot;, sName=&#x27;&quot;</span> + sName + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, sSex=&#x27;&quot;</span> + sSex + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">                <span class="string">&quot;, tId=&quot;</span> + tId +</span><br><span class="line">                <span class="string">&quot;, teacher=&quot;</span> + teacher +</span><br><span class="line">                <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-5-创建接口（在dao或者mapper层下）"><a href="#2-5-创建接口（在dao或者mapper层下）" class="headerlink" title="2.5.创建接口（在dao或者mapper层下）"></a>2.5.创建接口（在dao或者mapper层下）</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mihayo.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mihayo.entities.Student;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Mapper;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.annotations.Param;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ClassName: TestDao</span></span><br><span class="line"><span class="comment"> * Package: com.mihayo.dao</span></span><br><span class="line"><span class="comment"> * Description:</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: 余泽云</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Create</span>: 2023/9/2 - 21:22</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: v1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">StudenttDao</span> &#123;</span><br><span class="line">    List&lt;Student&gt; <span class="title function_">getList</span><span class="params">()</span>;</span><br><span class="line">    List&lt;Student&gt; <span class="title function_">getListName</span><span class="params">(<span class="meta">@Param(&quot;tName&quot;)</span> String tName, <span class="meta">@Param(&quot;tAge&quot;)</span> String tAge)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> <span class="title function_">updateList</span><span class="params">(Student student)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> <span class="title function_">insertList</span><span class="params">((Student student)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> <span class="title function_">deleteList</span><span class="params">((Student student)</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-6-配置StudentMapper-xml配置文件"><a href="#2-6-配置StudentMapper-xml配置文件" class="headerlink" title="2.6.配置StudentMapper.xml配置文件"></a>2.6.配置StudentMapper.xml配置文件</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span></span></span><br><span class="line"><span class="meta">		<span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">		<span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.mihayo.dao.TestDao&quot;</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">&quot;insertList&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;com.mihayo.entities.Student&quot;</span>&gt;</span></span><br><span class="line">		insert into YZY value (#&#123;tId&#125;,#&#123;tName&#125;,#&#123;tAge&#125;)</span><br><span class="line">	<span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">&quot;updateList&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;com.mihayo.entities.Student&quot;</span>&gt;</span></span><br><span class="line">		update YZY set t_age = #&#123;tAge&#125; where t_name = #&#123;tName&#125; and t_id = #&#123;tId&#125;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">delete</span> <span class="attr">id</span>=<span class="string">&quot;deleteList&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;com.mihayo.entities.Student&quot;</span>&gt;</span></span><br><span class="line">		delete from YZY where t_name = #&#123;tName&#125;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">delete</span>&gt;</span></span><br><span class="line"></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getList&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mihayo.entities.Student&quot;</span>&gt;</span></span><br><span class="line">		select * from YZY where</span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getListName&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.mihayo.entities.Student&quot;</span>&gt;</span></span><br><span class="line">		select * from YZY where 1=1</span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;tName != null and tName != &#x27;&#x27;&quot;</span>&gt;</span></span><br><span class="line">			and t_name = #&#123;tName&#125;</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot; tAge != null and tAge != &#x27;&#x27;&quot;</span>&gt;</span></span><br><span class="line">			and t_age = #&#123;tAge&#125;</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<ul>
<li><code>namespace</code>中的包名要和Dao&#x2F;Mapper接口的包名一致！</li>
<li>id:就是对应的namespace中的方法名；</li>
<li>resultType:Sql语句执行的返回值！</li>
<li>parameterType:参数类型！</li>
<li>增删改需要提交事务！</li>
</ul>
<p><strong>常见错误:</strong></p>
<ul>
<li>xml文件中注释不能出现中文报错，查看自己的是UTF-8还是GBK编码，改成为相应的就行。</li>
<li>标签不要匹配错！</li>
<li>resource绑定mapper，需要使用路径！</li>
<li>程序配置文件必须符合规范！</li>
<li>NullPointerException，没有注册到资源！</li>
<li>maven资源没有导出问题！</li>
</ul>
</blockquote>
<h4 id="2-7-编写测试类"><a href="#2-7-编写测试类" class="headerlink" title="2.7.编写测试类"></a>2.7.编写测试类</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.mihayo.service;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mihayo.dao.StudentDao;</span><br><span class="line"><span class="keyword">import</span> com.mihayo.util.MybatisUtil;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.session.SqlSession;</span><br><span class="line"><span class="keyword">import</span> org.junit.Test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ClassName: TestService</span></span><br><span class="line"><span class="comment"> * Package: com.mihayo.service</span></span><br><span class="line"><span class="comment"> * Description:</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: 余泽云</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Create</span>: 2023/9/2 - 21:39</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: v1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestService</span> &#123;</span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">getList</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> MybatisUtil.getSqlSession();</span><br><span class="line">        <span class="type">StudentDao</span> <span class="variable">studentDao</span> <span class="operator">=</span> sqlSession.getMapper(StudentDao.class);</span><br><span class="line">        List&lt;Student&gt; students = studentDao.getList();</span><br><span class="line">        <span class="keyword">for</span> (Student student : students) &#123;</span><br><span class="line">            System.out.println(student);</span><br><span class="line">        &#125;</span><br><span class="line">        sqlSession.close();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">insertList</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> MybatisUtil.getSqlSession();</span><br><span class="line">        <span class="type">StudentDao</span> <span class="variable">studentDao</span> <span class="operator">=</span> sqlSession.getMapper(StudentDao.class);</span><br><span class="line">        <span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> studenttDao.insertList(<span class="keyword">new</span> <span class="title class_">Student</span>(<span class="number">4</span>, <span class="string">&quot;岳云鹏&quot;</span>, <span class="string">&quot;20&quot;</span>));</span><br><span class="line">        <span class="keyword">if</span> (i == <span class="number">1</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;插入成功&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">updaList</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> MybatisUtil.getSqlSession();</span><br><span class="line">        <span class="type">StudentDao</span> <span class="variable">studentDao</span> <span class="operator">=</span> sqlSession.getMapper(StudentDao.class);</span><br><span class="line">        <span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> studenttDao.updateList(<span class="keyword">new</span> <span class="title class_">Student</span>(<span class="number">4</span>, <span class="string">&quot;岳云鹏&quot;</span>, <span class="string">&quot;21&quot;</span>));</span><br><span class="line">        <span class="keyword">if</span> (i == <span class="number">1</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;更新成功&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">deleteList</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> MybatisUtil.getSqlSession();</span><br><span class="line">        <span class="type">StudentDao</span> <span class="variable">studentDao</span> <span class="operator">=</span> sqlSession.getMapper(StudentDao.class);</span><br><span class="line">        <span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> studentDao.deleteList(<span class="keyword">new</span> <span class="title class_">Student</span>(<span class="number">4</span>, <span class="string">&quot;岳云鹏&quot;</span>, <span class="string">&quot;21&quot;</span>));</span><br><span class="line">        <span class="keyword">if</span> (i == <span class="number">1</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;删除成功&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>模糊查询怎么写？</p>
<ol>
<li><p>java代码执行的时候，传递通配符% %</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">List&lt;User&gt; userList = mapper.getUserLike(<span class="string">&quot;%李%&quot;</span>); </span><br></pre></td></tr></table></figure>
</li>
<li><p>在sql拼接中使用通配符！</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select * from mybatis.user where name like <span class="string">&quot;%&quot;</span>#&#123;value&#125;<span class="string">&quot;%&quot;</span></span><br></pre></td></tr></table></figure></li>
</ol>
</blockquote>
<h3 id="3-配置解析"><a href="#3-配置解析" class="headerlink" title="3.配置解析"></a>3.配置解析</h3><p><strong>MyBatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息。</strong></p>
<blockquote>
<p>configuration（配置）</p>
<p>properties（属性）<br>settings（设置）<br>typeAliases（类型别名）<br>typeHandlers（类型处理器）<br>objectFactory（对象工厂）<br>plugins（插件）<br>environments（环境配置）<br>environment（环境变量）<br>transactionManager（事务管理器）<br>dataSource（数据源）<br>databaseIdProvider（数据库厂商标识）<br>mappers（映射器）</p>
</blockquote>
<h4 id="3-1环境配置（environments）"><a href="#3-1环境配置（environments）" class="headerlink" title="3.1环境配置（environments）"></a>3.1环境配置（environments）</h4><p>Mybatis可以配置成适应多种环境</p>
<blockquote>
<ul>
<li><strong>不过要记住：尽管可以配置多个环境，但每个SqlSessionFactory实例只能选择一种环境。</strong></li>
<li>学会使用配置多套运行环境！</li>
<li>Mybatis默认的事务管理器就是JDBC、连接池：POOLED</li>
</ul>
</blockquote>
<h4 id="3-2-属性（properties）"><a href="#3-2-属性（properties）" class="headerlink" title="3.2 属性（properties）"></a>3.2 属性（properties）</h4><p>我们可以通过properties属性来实现引用配置文件，这些属性都是可外部配置且可动态替换的，既可以在典型的Java属性文件中配置，亦可通过properties元素的子元素来传递。</p>
<p>1.编写一个配置文件 <code>db.properties</code></p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">driver</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">url</span>=<span class="string">jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;allowPublicKeyRetrieval=true</span></span><br><span class="line"><span class="attr">username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">password</span>=<span class="string">123456</span></span><br></pre></td></tr></table></figure>

<p>2.在核心配置文件中映入</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--引入外部配置文件--&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">properties</span> <span class="attr">resource</span>=<span class="string">&quot;db.properties&quot;</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span> <span class="attr">value</span>=<span class="string">&quot;root&quot;</span>/&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;pwd&quot;</span> <span class="attr">value</span>=<span class="string">&quot;123456&quot;</span>/&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">properties</span>&gt;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<ul>
<li>可以直接引入外部文件</li>
<li>可以在其中增加一些属性配置</li>
<li>如果两个文件有同一个字段，优先使用外部配置文件的！</li>
</ul>
</blockquote>
<h4 id="3-3类型别名（typeAliases）"><a href="#3-3类型别名（typeAliases）" class="headerlink" title="3.3类型别名（typeAliases）"></a>3.3类型别名（typeAliases）</h4><ul>
<li>类型别名是为Java类型设置一个短的名字。</li>
<li><strong>存在的意义仅在于用来减少类完全限定名的冗余。</strong></li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--可以给实体类起别名--&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">typeAliases</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">typeAlias</span> <span class="attr">type</span>=<span class="string">&quot;com.kuang.pojo.User&quot;</span> <span class="attr">alias</span>=<span class="string">&quot;User&quot;</span> /&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">typeAliases</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>也可以指定一个包名，MyBatis会在包名下面搜索需要的JavaBean，比如：</li>
<li>扫描实体类的包，它的默认别名就为这个类的类名，首字母小写！</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--可以给实体类起别名--&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">typeAliases</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">package</span> <span class="attr">name</span>=<span class="string">&quot;com.kuang.pojo&quot;</span>/&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">typeAliases</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>在实体类比较少的时候，使用第一种方式。</li>
<li>如果实体类十分多，建议使用第二种。</li>
<li>第一种可以DIY别名，第二种则不行，如果非要改，需要在实体上增加注解</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">·<span class="meta">@Alias(&quot;user&quot;)</span></span><br><span class="line"><span class="comment">//实体类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-4设置"><a href="#3-4设置" class="headerlink" title="3.4设置"></a>3.4设置</h4><p>这是MyBatis中极为重要的调整设置，它们会改变MyBatis的运行时行为。<br><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946747.png" alt="在这里插入图片描述"><br><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946833.png" alt="在这里插入图片描述"></p>
<h4 id="3-5-其他配置"><a href="#3-5-其他配置" class="headerlink" title="3.5 其他配置"></a>3.5 其他配置</h4><ul>
<li>typeHandlers（类型处理器）</li>
<li>objectFactory（对象工厂）</li>
<li>plugins（插件）<ol>
<li>mybatis-generator-core</li>
<li>mybatis-plus</li>
<li>通用mapper</li>
</ol>
</li>
</ul>
<h4 id="3-6-映射器（mappers）"><a href="#3-6-映射器（mappers）" class="headerlink" title="3.6 映射器（mappers）"></a>3.6 映射器（mappers）</h4><p>MapperRegistry：注册绑定我们的Mapper文件；<br>方式一：【推荐使用】</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册！--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mappers</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mapper</span> <span class="attr">resource</span>=<span class="string">&quot;com/kuang/dao/UserMapper.xml&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mappers</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>方式二：使用class文件绑定注册</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册！--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mappers</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mapper</span> <span class="attr">class</span>=<span class="string">&quot;com.kuang.dao.UserMapper&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mappers</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>注意点：</p>
<ul>
<li>接口和它的Mapper配置文件必须同名！</li>
<li>接口和它的Mapper配置文件必须在同一个包下!</li>
</ul>
<p>方式三：使用扫描包进行注入绑定</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册！--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mappers</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">package</span> <span class="attr">name</span>=<span class="string">&quot;com.kuang.dao&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mappers</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>注意点：</p>
<ul>
<li>接口和它的Mapper配置文件必须同名！</li>
<li>接口和它的Mapper配置文件必须在同一个包下!</li>
</ul>
<p>练习：</p>
<ul>
<li>将数据库配置文件外部引入</li>
<li>实体类别名</li>
<li>保证UserMapper接口和UserMapper.xml改为一致！并且放在同一个包下！</li>
</ul>
<h4 id="3-7-生命周期和作用域"><a href="#3-7-生命周期和作用域" class="headerlink" title="3.7 生命周期和作用域"></a>3.7 生命周期和作用域</h4><p><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946929.png" alt="在这里插入图片描述"><br>生命周期和作用域是至关重要的，因为错误的使用会导致非常严重的<strong>并发问题</strong>。</p>
<p><strong>SqlSessionFactoryBuilder：</strong></p>
<ul>
<li>一旦创建了 SqlSessionFactory，就不再需要它了。</li>
<li>局部变量</li>
</ul>
<p><strong>SqlSessionFactory：</strong></p>
<ul>
<li>说白就是可以想象为：数据库连接池。</li>
<li>SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在，<strong>没有任何理由丢弃它或重新创建另一个实例</strong>。</li>
<li>SqlSessionFactory 的最佳作用域是应用作用域。</li>
<li>最简单的就是使用<strong>单例模式</strong>或者静态单例模式。</li>
</ul>
<p><strong>SqlSession：</strong></p>
<ul>
<li>连接到连接池的一个请求！</li>
<li>SqlSession 的实例不是线程安全的，因此是不能被共享的，所以它的最佳的作用域是请求或方法作用域。</li>
<li>用完后需要赶紧关闭，否则资源被占用！<br><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946016.png" alt="在这里插入图片描述"><br>这里的每一个Mapper，就代表一个具体的业务！</li>
</ul>
<h3 id="4、解决属性名和字段名不一致的问题"><a href="#4、解决属性名和字段名不一致的问题" class="headerlink" title="4、解决属性名和字段名不一致的问题"></a>4、解决属性名和字段名不一致的问题</h3><h4 id="4-1-问题"><a href="#4-1-问题" class="headerlink" title="4.1 问题"></a>4.1 问题</h4><p>数据库中的字段<br><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946094.png" alt="在这里插入图片描述"><br>新建一个项目，拷贝之前的，测试实体类字段不一致的情况</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>测试出现问题<br><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946180.png" alt="在这里插入图片描述"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//    select * from mybatis.user where id = #&#123;id&#125;</span></span><br><span class="line"><span class="comment">// 类型处理器</span></span><br><span class="line"><span class="comment">//    select id,name,pwd from mybatis.user where id = #&#123;id&#125;</span></span><br></pre></td></tr></table></figure>

<p>解决方法：</p>
<ul>
<li><p><strong>起别名</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getUserById&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;int&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;user&quot;</span>&gt;</span></span><br><span class="line">    select id,name,pwd as password from mybatis.user where id = #&#123;id&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>resultMap解决</strong></p>
</li>
</ul>
<h4 id="4-2-resultMap"><a href="#4-2-resultMap" class="headerlink" title="4.2 resultMap"></a>4.2 resultMap</h4><p>结果集映射</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">id name pwd</span><br><span class="line">id name password</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--  结果集映射  --&gt;</span><br><span class="line">&lt;resultMap id=<span class="string">&quot;UserMap&quot;</span> type=<span class="string">&quot;User&quot;</span>&gt;</span><br><span class="line">    &lt;!--column数据库中的字段，property实体类中的属性--&gt;</span><br><span class="line">    &lt;result column=<span class="string">&quot;id&quot;</span> property=<span class="string">&quot;id&quot;</span> /&gt;</span><br><span class="line">    &lt;result column=<span class="string">&quot;name&quot;</span> property=<span class="string">&quot;name&quot;</span> /&gt;</span><br><span class="line">    &lt;result column=<span class="string">&quot;pwd&quot;</span> property=<span class="string">&quot;password&quot;</span> /&gt;</span><br><span class="line">&lt;/resultMap&gt;</span><br><span class="line"></span><br><span class="line">&lt;select id=<span class="string">&quot;getUserById&quot;</span> parameterType=<span class="string">&quot;int&quot;</span> resultMap=<span class="string">&quot;UserMap&quot;</span>&gt;</span><br><span class="line">    select * from mybatis.user <span class="type">where</span> <span class="variable">id</span> <span class="operator">=</span> #&#123;id&#125;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>resultMap 元素是 MyBatis 中最重要最强大的元素。</li>
<li>ResultMap 的设计思想是，对简单的语句做到零配置，对于复杂一点的语句，只需要描述语句之间的关系就行了。</li>
<li>ResultMap 的优秀之处——你完全可以不用显式地配置它们。</li>
<li>如果这个世界总是这么简单就好了。</li>
</ul>
<h3 id="5、日志（2020-10-24）"><a href="#5、日志（2020-10-24）" class="headerlink" title="5、日志（2020-10-24）"></a>5、日志（2020-10-24）</h3><h4 id="5-1-日志工厂"><a href="#5-1-日志工厂" class="headerlink" title="5.1 日志工厂"></a>5.1 日志工厂</h4><p>如果一个数据库操作出现了异常，我们需要排错。日志就是最好的助手！<br>曾经：sout、debug<br>现在：日志工厂！</p>
<p><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946287.png" alt="在这里插入图片描述"></p>
<ul>
<li>SLF4J</li>
<li>LOG4J 【掌握】</li>
<li>LOG4J2</li>
<li>JDK_LOGGING</li>
<li>COMMONS_LOGGING</li>
<li>STDOUT_LOGGING【掌握】</li>
<li>NO_LOGGING</li>
</ul>
<p>在Mybatis中具体使用哪一个日志实现，在设置中设定！</p>
<p><strong>STDOUT_LOGGING</strong>标准日志输出<br>在mybatis-config.xml核心配置文件中，配置我们的日志！</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">settings</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">setting</span> <span class="attr">name</span>=<span class="string">&quot;logImpl&quot;</span> <span class="attr">value</span>=<span class="string">&quot;STDOUT_LOGGING&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">settings</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946386.png" alt="在这里插入图片描述"></p>
<h4 id="6-2-Log4j"><a href="#6-2-Log4j" class="headerlink" title="6.2 Log4j"></a>6.2 Log4j</h4><p>什么是Log4j？</p>
<ul>
<li>Log4j是Apache的一个开源项目，通过使用Log4j，我们可以控制日志信息输送的目的地是控制台、文件、GUI组件</li>
<li>我们也可以控制每一条日志的输出格式；</li>
<li>通过定义每一条日志信息的级别，我们能够更加细致地控制日志的生成过程。</li>
<li>可以通过一个配置文件来灵活地进行配置，而不需要修改应用的代码。</li>
</ul>
<p>1.先在pom.xml文件中导入log4j的依赖包</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- https://mvnrepository.com/artifact/log4j/log4j --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>log4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>log4j<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2.17<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>2.在resources文件夹下建立log4j.properties文件进行配置</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#将等级为DEBUG的日志信息输出到console和file这两个目的地，console和file的定义在下面的代码</span></span><br><span class="line"><span class="attr">log4j.rootLogger</span> = <span class="string">DEBUG,console ,file</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">#控制台输出的相关设置</span></span><br><span class="line"><span class="attr">log4j.appender.console</span> = <span class="string">org.apache.log4j.ConsoleAppender</span></span><br><span class="line"><span class="attr">log4j.appender.console.Target</span> = <span class="string">System.out</span></span><br><span class="line"><span class="attr">log4j.appender.console.Threshold</span> = <span class="string">DEBUG</span></span><br><span class="line"><span class="attr">log4j.appender.console.layout</span> = <span class="string">org.apache.log4j.PatternLayout</span></span><br><span class="line"><span class="attr">log4j.appender.console.layout.ConversionPattern</span> =  <span class="string">[%c]-%m%n</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">#文件输出的相关设置</span></span><br><span class="line"><span class="attr">log4j.appender.file</span> = <span class="string">org.apache.log4j.RollingFileAppender</span></span><br><span class="line"><span class="attr">log4j.appender.file.File</span> = <span class="string">./log/kuang.log</span></span><br><span class="line"><span class="attr">log4j.appender.file.MaxFileSize</span> = <span class="string">10mb</span></span><br><span class="line"><span class="attr">log4j.appender.file.Threshold</span> = <span class="string">DEBUG</span></span><br><span class="line"><span class="attr">log4j.appender.file.layout</span> = <span class="string">org.apache.log4j.PatternLayout</span></span><br><span class="line"><span class="attr">log4j.appender.file.layout.ConversionPattern</span> = <span class="string">[%p][%d&#123;yy-MM-dd&#125;][%c]%m%n</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">#日志输出级别</span></span><br><span class="line"><span class="attr">log4j.logger.org.mybatis</span>=<span class="string">DEBUG</span></span><br><span class="line"><span class="attr">log4j.logger.java.sql</span>=<span class="string">DEBUG</span></span><br><span class="line"><span class="attr">log4j.logger.java.sql.Statement</span>=<span class="string">DEBUG</span></span><br><span class="line"><span class="attr">log4j.logger.java.sql.ResultSet</span>=<span class="string">DEBUG</span></span><br><span class="line"><span class="attr">log4j.logger.java.sql.PreparedStatement</span>=<span class="string">DEBUG</span></span><br></pre></td></tr></table></figure>

<p>3.在mybatis-config.xml核心配置文件中，配置log4j为日志的实现！</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">settings</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">setting</span> <span class="attr">name</span>=<span class="string">&quot;logImpl&quot;</span> <span class="attr">value</span>=<span class="string">&quot;LOG4J&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">settings</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>4.Log4j的使用，直接测试运行<br><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946471.png" alt="在这里插入图片描述"><br><strong>简单使用</strong></p>
<ol>
<li>在要使用Log4j的测试类中，导入包import org.apache.log4j.Logger;</li>
<li>日志对象，参数为当前类的class</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="type">Logger</span> <span class="variable">logger</span> <span class="operator">=</span> Logger.getLogger(UserDaoTest.class);</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>日志级别</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">logger.info(<span class="string">&quot;info:进入了testLog4j&quot;</span>);</span><br><span class="line">logger.debug(<span class="string">&quot;DEBUG:进入了testLog4j&quot;</span>);</span><br><span class="line">logger.error(<span class="string">&quot;erro:进入了testLog4j&quot;</span>);</span><br></pre></td></tr></table></figure>

<ol start="4">
<li>之后可在log文件夹中查看日志文件信息</li>
</ol>
<h3 id="6、分页"><a href="#6、分页" class="headerlink" title="6、分页"></a>6、分页</h3><p><strong>思考：为什么要分页！</strong></p>
<ul>
<li>减少数据的处理量</li>
</ul>
<h4 id="6-1-使用Limit分页"><a href="#6-1-使用Limit分页" class="headerlink" title="6.1 使用Limit分页"></a>6.1 使用Limit分页</h4><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">语法：<span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">from</span> <span class="keyword">user</span> limit startIndex,pageSize</span><br><span class="line"><span class="keyword">SELECT</span>  <span class="operator">*</span> <span class="keyword">from</span> <span class="keyword">user</span> limit <span class="number">3</span> #[<span class="number">0</span>,n]</span><br></pre></td></tr></table></figure>

<p><strong>使用Mybatis实现分页，核心SQL</strong></p>
<ol>
<li>接口</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//分页</span></span><br><span class="line">List&lt;User&gt; <span class="title function_">getUserByLimit</span><span class="params">(Map&lt;String,Integer&gt; map)</span>;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>Mapper.xml</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--    分页--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getUserByLimit&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;map&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;UserMap&quot;</span>&gt;</span></span><br><span class="line">        select * from mybatis.user limit #&#123;startIndex&#125;,#&#123;pageSize&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="3">
<li>测试</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">getUserByLimit</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> MybatisUtils.getSqlSession();</span><br><span class="line">    <span class="type">UserMapper</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(UserMapper.class);</span><br><span class="line"></span><br><span class="line">    HashMap&lt;String, Integer&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;String, Integer&gt;();</span><br><span class="line">    map.put(<span class="string">&quot;startIndex&quot;</span>,<span class="number">0</span>);</span><br><span class="line">    map.put(<span class="string">&quot;pageSize&quot;</span>,<span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">    List&lt;User&gt; userList = mapper.getUserByLimit(map);</span><br><span class="line">    <span class="keyword">for</span> (User user : userList) &#123;</span><br><span class="line">        System.out.println(user);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    sqlSession.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="6-2-RowBounds分页"><a href="#6-2-RowBounds分页" class="headerlink" title="6.2 RowBounds分页"></a>6.2 RowBounds分页</h4><p>不再使用SQL实现分页</p>
<ol>
<li>接口</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//分页2</span></span><br><span class="line">List&lt;User&gt; <span class="title function_">getUserByRowBounds</span><span class="params">()</span>;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>Mapper.xml</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--    分页2--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getUserByRowBounds&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;UserMap&quot;</span>&gt;</span></span><br><span class="line">        select * from mybatis.user</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="3">
<li>测试</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">getUserByRowBounds</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> MybatisUtils.getSqlSession();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//RowBounds实现</span></span><br><span class="line">    <span class="type">RowBounds</span> <span class="variable">rowBounds</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RowBounds</span>(<span class="number">0</span>, <span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通过java代码层面实现分页</span></span><br><span class="line">    List&lt;User&gt; userList = sqlSession.selectList(<span class="string">&quot;com.kuang.dao.UserMapper.getUserByRowBounds&quot;</span>,<span class="literal">null</span>,rowBounds);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (User user : userList) &#123;</span><br><span class="line">        System.out.println(user);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    sqlSession.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="6-3-分页插件"><a href="#6-3-分页插件" class="headerlink" title="6.3 分页插件"></a>6.3 分页插件</h4><p><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946566.png" alt="在这里插入图片描述"><br>了解即可，使用时，需要知道是什么东西！</p>
<h3 id="7、使用注解开发"><a href="#7、使用注解开发" class="headerlink" title="7、使用注解开发"></a>7、使用注解开发</h3><h4 id="7-1-面向接口编程"><a href="#7-1-面向接口编程" class="headerlink" title="7.1 面向接口编程"></a>7.1 面向接口编程</h4><ul>
<li>之前学过面向对象编程，也学习过接口，但在真正的开发中，很多时候会选择面向接口编程。</li>
<li><strong>根本原因：解耦，可拓展，提高复用，分层开发中，上层不用管具体的实现，大家都遵守共同的标准，使得开发变得容易，规范性更好</strong></li>
<li>在一个面向对象的系统中，系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下，各个对象内部是如何实现自己的，对系统设计人员来讲就不那么重要了；</li>
<li>而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信，大到各模块之间的交互，在系统设计之初都是要着重考虑的，这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。</li>
</ul>
<h4 id="7-2-使用注解开发"><a href="#7-2-使用注解开发" class="headerlink" title="7.2 使用注解开发"></a>7.2 使用注解开发</h4><ol>
<li>注解在UserMapper接口上实现，并删除UserMapper.xml文件</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Select(&quot;select * from user&quot;)</span></span><br><span class="line">List&lt;User&gt; <span class="title function_">getUsers</span><span class="params">()</span>;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>需要在mybatis-config.xml核心配置文件中绑定接口</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--绑定接口！--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mappers</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mapper</span> <span class="attr">class</span>=<span class="string">&quot;com.kuang.dao.UserMapper&quot;</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mappers</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="3">
<li>测试</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">getUsers</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="type">SqlSession</span> <span class="variable">sqlSession</span> <span class="operator">=</span> MybatisUtils.getSqlSession();</span><br><span class="line">    <span class="type">UserMapper</span> <span class="variable">mapper</span> <span class="operator">=</span> sqlSession.getMapper(UserMapper.class);</span><br><span class="line">    List&lt;User&gt; users = mapper.getUsers();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (User user : users) &#123;</span><br><span class="line">        System.out.println(user);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    sqlSession.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>本质：反射机制实现<br>底层：动态代理！</p>
<p><strong>Mybatis详细的执行流程！（之后应用的多了详细再走一遍）</strong></p>
<h4 id="7-3-CRUD"><a href="#7-3-CRUD" class="headerlink" title="7.3 CRUD"></a>7.3 CRUD</h4><ol>
<li>在MybatisUtils工具类创建的时候实现自动提交事务！</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> SqlSession <span class="title function_">getSqlSession</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> sqlSessionFactory.openSession(<span class="literal">true</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>编写接口，增加注解</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserMapper</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Select(&quot;select * from user&quot;)</span></span><br><span class="line">    List&lt;User&gt; <span class="title function_">getUsers</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//方法存在多个参数，所有参数前面必须加上@Param(&quot;id&quot;)注解</span></span><br><span class="line">    <span class="meta">@Select(&quot;select * from user where id=#&#123;id&#125;&quot;)</span></span><br><span class="line">    User <span class="title function_">getUserById</span><span class="params">(<span class="meta">@Param(&quot;id&quot;)</span> <span class="type">int</span> id)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Insert(&quot;insert into user (id,name,pwd) values(#&#123;id&#125;,#&#123;name&#125;,#&#123;password&#125;)&quot;)</span></span><br><span class="line">    <span class="type">int</span> <span class="title function_">addUser</span><span class="params">(User user)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Update(&quot;update user set name=#&#123;name&#125;,pwd=#&#123;password&#125; where id=#&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="type">int</span> <span class="title function_">updateUser</span><span class="params">(User user)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Delete(&quot;delete from user where id = #&#123;uid&#125;&quot;)</span></span><br><span class="line">    <span class="type">int</span> <span class="title function_">deleteUser</span><span class="params">(<span class="meta">@Param(&quot;uid&quot;)</span> <span class="type">int</span> id)</span>;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>测试类</li>
</ol>
<p>【注意：我们必须要将接口注册绑定到我们的核心配置文件中！】</p>
<p><strong>关于@Param()注解</strong></p>
<ul>
<li>基本类型的参数或者String类型，需要加上</li>
<li>引用类型不需要加</li>
<li>如果只有一个基本类型的话，可以忽略，但是建议都加上！</li>
<li>我们在SQL中引用的就是我们这里的@Param(“”)中设定的属性名！<br><strong>#{}和${}区别</strong></li>
</ul>
<h3 id="8、Lombok（偷懒的话可以使用）"><a href="#8、Lombok（偷懒的话可以使用）" class="headerlink" title="8、Lombok（偷懒的话可以使用）"></a>8、Lombok（偷懒的话可以使用）</h3><p>使用步骤：</p>
<ol>
<li>在IDEA中安装Lombok插件！</li>
<li>在项目pom.xml文件中导入Lombok的jar包</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.18.10<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="3">
<li>在实体类上加注解即可！</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Getter</span> and <span class="meta">@Setter</span></span><br><span class="line"><span class="meta">@FieldNameConstants</span></span><br><span class="line"><span class="meta">@ToString</span></span><br><span class="line"><span class="meta">@EqualsAndHashCode</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span>, <span class="meta">@RequiredArgsConstructor</span> and <span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@Log</span>, <span class="meta">@Log4j</span>, <span class="meta">@Log4j2</span>, <span class="meta">@Slf4j</span>, <span class="meta">@XSlf4j</span>, <span class="meta">@CommonsLog</span>, <span class="meta">@JBossLog</span>, <span class="meta">@Flogger</span>, <span class="meta">@CustomLog</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@Builder</span></span><br><span class="line"><span class="meta">@SuperBuilder</span></span><br><span class="line"><span class="meta">@Singular</span></span><br><span class="line"><span class="meta">@Delegate</span></span><br><span class="line"><span class="meta">@Value</span></span><br><span class="line"><span class="meta">@Accessors</span></span><br><span class="line"><span class="meta">@Wither</span></span><br><span class="line"><span class="meta">@With</span></span><br><span class="line"><span class="meta">@SneakyThrows</span></span><br></pre></td></tr></table></figure>

<p>说明：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span>:无参构造、get、set、toString、hashCode、equals</span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@EqualsAndHashCode</span></span><br><span class="line"><span class="meta">@ToString</span></span><br><span class="line"><span class="meta">@Getter</span> and <span class="meta">@Setter</span></span><br></pre></td></tr></table></figure>

<h3 id="9、多对一处理"><a href="#9、多对一处理" class="headerlink" title="9、多对一处理"></a>9、多对一处理</h3><p>多对一：</p>
<ul>
<li>多个学生，对应一个老师</li>
<li>对于学生而言，<strong>关联</strong>–多个学生，关联一个老师【多对一】</li>
<li>对于老师而言，<strong>集合</strong>–一个老师，有很多个学生【一对多】</li>
</ul>
<p>SQL语句：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> `teacher` (</span><br><span class="line">	`id` <span class="type">INT</span>(<span class="number">10</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">	`name` <span class="type">VARCHAR</span>(<span class="number">30</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">	<span class="keyword">PRIMARY</span> KEY (`id`)</span><br><span class="line">)ENGINE <span class="operator">=</span> INNODB <span class="keyword">DEFAULT</span> CHARSET<span class="operator">=</span>utf8</span><br><span class="line"></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> teacher(`id`,`name`) <span class="keyword">VALUES</span> (<span class="number">1</span>,<span class="string">&#x27;秦老师&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> `student` (</span><br><span class="line">	`id` <span class="type">INT</span>(<span class="number">10</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">	`name` <span class="type">VARCHAR</span>(<span class="number">30</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">	`tid` <span class="type">INT</span>(<span class="number">10</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">	<span class="keyword">PRIMARY</span> KEY (`id`),</span><br><span class="line">	KEY `fktid`(`tid`),</span><br><span class="line">	<span class="keyword">CONSTRAINT</span> `fktid` <span class="keyword">FOREIGN</span> KEY (`tid`) <span class="keyword">REFERENCES</span> `teacher` (`id`)</span><br><span class="line">)ENGINE <span class="operator">=</span> INNODB <span class="keyword">DEFAULT</span> CHARSET<span class="operator">=</span>utf8</span><br><span class="line"></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> `student`(`id`,`name`,`tid`) <span class="keyword">VALUES</span> (<span class="string">&#x27;1&#x27;</span>,<span class="string">&#x27;小明&#x27;</span>,<span class="string">&#x27;1&#x27;</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> `student`(`id`,`name`,`tid`) <span class="keyword">VALUES</span> (<span class="string">&#x27;2&#x27;</span>,<span class="string">&#x27;小红&#x27;</span>,<span class="string">&#x27;1&#x27;</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> `student`(`id`,`name`,`tid`) <span class="keyword">VALUES</span> (<span class="string">&#x27;3&#x27;</span>,<span class="string">&#x27;小张&#x27;</span>,<span class="string">&#x27;1&#x27;</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> `student`(`id`,`name`,`tid`) <span class="keyword">VALUES</span> (<span class="string">&#x27;4&#x27;</span>,<span class="string">&#x27;小李&#x27;</span>,<span class="string">&#x27;1&#x27;</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> `student`(`id`,`name`,`tid`) <span class="keyword">VALUES</span> (<span class="string">&#x27;5&#x27;</span>,<span class="string">&#x27;小王&#x27;</span>,<span class="string">&#x27;1&#x27;</span>);</span><br></pre></td></tr></table></figure>

<h4 id="9-1测试环境搭建"><a href="#9-1测试环境搭建" class="headerlink" title="9.1测试环境搭建"></a>9.1测试环境搭建</h4><ol>
<li>导入Lombok</li>
<li>新建实体类Teacher，Student</li>
<li>建立Mapper接口</li>
<li>建立Mapper.XML文件</li>
<li>在核心配置文件中绑定注册我们的Mapper接口或者文件！【方式很多,随心选】</li>
<li>测试查询是否能够成功！</li>
</ol>
<h4 id="9-2-按照结果嵌套处理"><a href="#9-2-按照结果嵌套处理" class="headerlink" title="9.2 按照结果嵌套处理"></a>9.2 按照结果嵌套处理</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--按照结果嵌套处理    --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getStudent2&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;StudentTeacher2&quot;</span>&gt;</span></span><br><span class="line">    select s.id sid,s.name sname,t.name tname</span><br><span class="line">    from mybatis.student s,mybatis.teacher t</span><br><span class="line">    where s.tid = t.id</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;StudentTeacher2&quot;</span> <span class="attr">type</span>=<span class="string">&quot;Student&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span> <span class="attr">column</span>=<span class="string">&quot;sid&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;name&quot;</span> <span class="attr">column</span>=<span class="string">&quot;sname&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">association</span> <span class="attr">property</span>=<span class="string">&quot;teacher&quot;</span> <span class="attr">javaType</span>=<span class="string">&quot;Teacher&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;name&quot;</span> <span class="attr">column</span>=<span class="string">&quot;tname&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">association</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="9-3按照查询嵌套处理"><a href="#9-3按照查询嵌套处理" class="headerlink" title="9.3按照查询嵌套处理"></a>9.3按照查询嵌套处理</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">  思路：</span></span><br><span class="line"><span class="comment">      1.查询所有的学生信息</span></span><br><span class="line"><span class="comment">      2.根据查询出来的学生的tid，寻找对应的老师！ 子查询--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getStudent&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;StudentTeacher&quot;</span>&gt;</span></span><br><span class="line">    select * from mybatis.student</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;StudentTeacher&quot;</span> <span class="attr">type</span>=<span class="string">&quot;Student&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span> <span class="attr">column</span>=<span class="string">&quot;id&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;name&quot;</span> <span class="attr">column</span>=<span class="string">&quot;name&quot;</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--  复杂的属性，我们需要单独处理 对象：association 集合：collection      --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">association</span> <span class="attr">property</span>=<span class="string">&quot;teacher&quot;</span> <span class="attr">column</span>=<span class="string">&quot;tid&quot;</span> <span class="attr">javaType</span>=<span class="string">&quot;Teacher&quot;</span> <span class="attr">select</span>=<span class="string">&quot;getTeacher&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getTeacher&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;Teacher&quot;</span>&gt;</span></span><br><span class="line">    select * from mybatis.teacher where id = #&#123;id&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>回顾Mysql多对一查询方式：</p>
<ul>
<li>子查询</li>
<li>联表查询</li>
</ul>
<h3 id="10-、一对多处理"><a href="#10-、一对多处理" class="headerlink" title="10 、一对多处理"></a>10 、一对多处理</h3><p>比如：一个老师拥有多个学生！<br>对于老师而言，就是一对多的关系！</p>
<h4 id="10-1-环境搭建"><a href="#10-1-环境搭建" class="headerlink" title="10.1 环境搭建"></a>10.1 环境搭建</h4><ol>
<li>环境搭建，和刚才一样<br><strong>实体类：</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Student</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> tid;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Teacher</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//一个老师拥有多个学生</span></span><br><span class="line">    <span class="keyword">private</span> List&lt;Student&gt; students;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="10-2按照结果嵌套处理"><a href="#10-2按照结果嵌套处理" class="headerlink" title="10.2按照结果嵌套处理"></a>10.2按照结果嵌套处理</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--    按结果嵌套查询--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getTeacher&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;TeacherStudent&quot;</span>&gt;</span></span><br><span class="line">        SELECT  s.id sid,s.name sname,t.name tname,t.id,tid</span><br><span class="line">        from student s,teacher t</span><br><span class="line">        where s.tid = t.id and t.id = #&#123;tid&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;TeacherStudent&quot;</span> <span class="attr">type</span>=<span class="string">&quot;Teacher&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span> <span class="attr">column</span>=<span class="string">&quot;tid&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;name&quot;</span> <span class="attr">column</span>=<span class="string">&quot;tname&quot;</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--  复杂的属性，我们需要单独处理 对象：association 集合：collection</span></span><br><span class="line"><span class="comment">         javaType=&quot;&quot; 指定属性的类型！</span></span><br><span class="line"><span class="comment">         集合中的泛型信息，我们使用ofType获取</span></span><br><span class="line"><span class="comment">         --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">collection</span> <span class="attr">property</span>=<span class="string">&quot;students&quot;</span> <span class="attr">ofType</span>=<span class="string">&quot;Student&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span> <span class="attr">column</span>=<span class="string">&quot;sid&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;name&quot;</span> <span class="attr">column</span>=<span class="string">&quot;sname&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;tid&quot;</span> <span class="attr">column</span>=<span class="string">&quot;tid&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">collection</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="10-3按照查询嵌套处理"><a href="#10-3按照查询嵌套处理" class="headerlink" title="10.3按照查询嵌套处理"></a>10.3按照查询嵌套处理</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getTeacher2&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;TeacherStudent2&quot;</span>&gt;</span></span><br><span class="line">    select * from mybatis.teacher where id = #&#123;tid&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;TeacherStudent2&quot;</span> <span class="attr">type</span>=<span class="string">&quot;Teacher&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">collection</span> <span class="attr">property</span>=<span class="string">&quot;students&quot;</span> <span class="attr">javaType</span>=<span class="string">&quot;ArrayList&quot;</span> <span class="attr">ofType</span>=<span class="string">&quot;Student&quot;</span> <span class="attr">select</span>=<span class="string">&quot;getStudentByTeacherId&quot;</span> <span class="attr">column</span>=<span class="string">&quot;id&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getStudentByTeacherId&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;Student&quot;</span>&gt;</span></span><br><span class="line">    select * from  mybatis.student where tid = #&#123;tid&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="10-4小结"><a href="#10-4小结" class="headerlink" title="10.4小结"></a>10.4小结</h4><blockquote>
<ol>
<li>关联-association【多对一】</li>
<li>集合-collection【一对多】</li>
<li>javaType &amp; ofType<ol>
<li>javaType 用来指定实体类中属性的类型</li>
<li>ofType 用来指定映射到List或者集合中的pojo类型，泛型中的约束类型！</li>
</ol>
</li>
</ol>
<p><strong>注意点：</strong></p>
<ul>
<li>保证SQL的可读性，尽量保证通俗易懂</li>
<li>注意一对多和多对一中，属性名和字段的问题！</li>
<li>如果问题不好排查错误，可以使用日志，建议使用Log4j</li>
</ul>
<p><strong>面试高频</strong></p>
<ul>
<li>Mysql引擎</li>
<li>InnoDB底层原理</li>
<li>索引</li>
<li>索引优化</li>
</ul>
</blockquote>
<h3 id="11、动态SQL"><a href="#11、动态SQL" class="headerlink" title="11、动态SQL"></a>11、动态SQL</h3><p><strong>什么是动态SQL：动态SQL就是 指根据不同的条件生成不同的SQL语句</strong></p>
<p>利用动态SQL这一特性可以彻底摆脱这种痛苦。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*在 MyBatis 之前的版本中，需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式，MyBatis 3 替换了之前的大部分元素，大大精简了元素种类，现在要学习的元素种类比原来的一半还要少。*/</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span></span><br><span class="line"><span class="title function_">choose</span> <span class="params">(when, otherwise)</span></span><br><span class="line">trim (where, set)</span><br><span class="line">foreach</span><br></pre></td></tr></table></figure>

<h4 id="11-1搭建环境"><a href="#11-1搭建环境" class="headerlink" title="11.1搭建环境"></a>11.1搭建环境</h4><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> `blog`(</span><br><span class="line">	`id` <span class="type">VARCHAR</span>(<span class="number">50</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span> COMMENT <span class="string">&#x27;博客id&#x27;</span>,</span><br><span class="line">	`title` <span class="type">VARCHAR</span>(<span class="number">100</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span> COMMENT <span class="string">&#x27;博客标题&#x27;</span>,</span><br><span class="line">	`author` <span class="type">VARCHAR</span>(<span class="number">30</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span> COMMENT <span class="string">&#x27;博客作者&#x27;</span>,</span><br><span class="line">	`create_time` DATETIME <span class="keyword">NOT</span> <span class="keyword">NULL</span> COMMENT <span class="string">&#x27;创建时间&#x27;</span>,</span><br><span class="line">	`views` <span class="type">INT</span>(<span class="number">30</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span> COMMENT <span class="string">&#x27;浏览量&#x27;</span></span><br><span class="line">)ENGINE<span class="operator">=</span>INNODB <span class="keyword">DEFAULT</span> CHARSET<span class="operator">=</span>utf8</span><br></pre></td></tr></table></figure>

<p><strong>创建一个基础工程</strong></p>
<ol>
<li>导包</li>
<li>编写配置文件</li>
<li>编写实体类</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Blog</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line">    <span class="keyword">private</span> String title;</span><br><span class="line">    <span class="keyword">private</span> String author;</span><br><span class="line">    <span class="keyword">private</span> Date createTime; <span class="comment">//属性名和字段名不一致</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> views;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="4">
<li>编写实体类对应Mapper接口和Mapper.XML文件</li>
</ol>
<h3 id="IF"><a href="#IF" class="headerlink" title="IF"></a>IF</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;queryBlogIF&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;map&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;Blog&quot;</span>&gt;</span></span><br><span class="line">    select * from mybatis.blog where 1=1</span><br><span class="line">    <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;title != null&quot;</span>&gt;</span></span><br><span class="line">        and title = #&#123;title&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;author != null&quot;</span>&gt;</span></span><br><span class="line">        and author = #&#123;author&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="choose-when-otherwise"><a href="#choose-when-otherwise" class="headerlink" title="choose (when, otherwise)"></a>choose (when, otherwise)</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;queryBlogChoose&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;map&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;Blog&quot;</span>&gt;</span></span><br><span class="line">    select * from mybatis.blog</span><br><span class="line">    <span class="tag">&lt;<span class="name">where</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">choose</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">&quot;title != null&quot;</span>&gt;</span></span><br><span class="line">                title = #&#123;title&#125;</span><br><span class="line">            <span class="tag">&lt;/<span class="name">when</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">&quot;author != null&quot;</span>&gt;</span></span><br><span class="line">                and author = #&#123;author&#125;</span><br><span class="line">            <span class="tag">&lt;/<span class="name">when</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">otherwise</span>&gt;</span></span><br><span class="line">                and views = #&#123;views&#125;</span><br><span class="line">            <span class="tag">&lt;/<span class="name">otherwise</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">choose</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">where</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="trim-where-set"><a href="#trim-where-set" class="headerlink" title="trim (where, set)"></a>trim (where, set)</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;queryBlogIF&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;map&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;Blog&quot;</span>&gt;</span></span><br><span class="line">    select * from mybatis.blog</span><br><span class="line">    <span class="tag">&lt;<span class="name">where</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;title != null&quot;</span>&gt;</span></span><br><span class="line">            and title = #&#123;title&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;author != null&quot;</span>&gt;</span></span><br><span class="line">            and author = #&#123;author&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">where</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">&quot;updateBlog&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;map&quot;</span>&gt;</span></span><br><span class="line">    update mybatis.blog</span><br><span class="line">    <span class="tag">&lt;<span class="name">set</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;title != null&quot;</span>&gt;</span></span><br><span class="line">            title = #&#123;title&#125;,</span><br><span class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;author != null&quot;</span>&gt;</span></span><br><span class="line">            author = #&#123;author&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">set</span>&gt;</span></span><br><span class="line">    where id = #&#123;id&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>所谓的动态SQL，本质还是SQL语句，只是我们可以在SQL层面，去执行一个逻辑代码</strong></p>
<h4 id="Foreach"><a href="#Foreach" class="headerlink" title="Foreach"></a>Foreach</h4><ul>
<li>动态 SQL 的另一个常见使用场景是对集合进行遍历（尤其是在构建 IN 条件语句的时候）。</li>
<li>foreach 元素的功能非常强大，它允许你指定一个集合，声明可以在元素体内使用的集合项（item）和索引（index）变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符，看它多智能！</li>
<li>提示你可以将任何可迭代对象（如 List、Set 等）、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时，index 是当前迭代的序号，item 的值是本次迭代获取到的元素。当使用 Map 对象（或者 Map.Entry 对象的集合）时，index 是键，item 是值。</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--select * from blog where 1=1 and (id=1 or id=2 or id=3)</span></span><br><span class="line"><span class="comment">    我们现在传递一个万能的map，这map中可以存在一个集合！</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;queryBlogForeach&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;map&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;Blog&quot;</span>&gt;</span></span><br><span class="line">    select * from mybatis.blog</span><br><span class="line">    <span class="tag">&lt;<span class="name">where</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">foreach</span> <span class="attr">collection</span>=<span class="string">&quot;ids&quot;</span> <span class="attr">item</span>=<span class="string">&quot;id&quot;</span> <span class="attr">open</span>=<span class="string">&quot;and (&quot;</span> <span class="attr">close</span>=<span class="string">&quot;)&quot;</span> <span class="attr">separator</span>=<span class="string">&quot;or&quot;</span>&gt;</span></span><br><span class="line">            id = #&#123;id&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">foreach</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">where</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>动态SQL就是在拼接SQL语句，我们只要保证SQL的正确性，按照SQL的格式，去排列组合就可以了。<br>建议：</p>
<ul>
<li>先在Mysql中写出完整的SQL，再对应的去修改成我们的动态SQL实现通用即可！</li>
</ul>
<h4 id="SQL片段"><a href="#SQL片段" class="headerlink" title="SQL片段"></a>SQL片段</h4><p>有的时候，我们可以能会将一些功能的部分抽取出来，方便复用！</p>
<ol>
<li>使用SQL标签抽取公共的部分</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">sql</span> <span class="attr">id</span>=<span class="string">&quot;if-title-author&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;title != null&quot;</span>&gt;</span></span><br><span class="line">        title = #&#123;title&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;author != null&quot;</span>&gt;</span></span><br><span class="line">        and author = #&#123;author&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">sql</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="2">
<li>在需要使用的地方使用Include标签引用即可</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;queryBlogIF&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;map&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;Blog&quot;</span>&gt;</span></span><br><span class="line">    select * from mybatis.blog</span><br><span class="line">    <span class="tag">&lt;<span class="name">where</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">include</span> <span class="attr">refid</span>=<span class="string">&quot;if-title-author&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">include</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">where</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong>注意事项：</strong></p>
<ul>
<li>最好基于单表来定义SQL片段！</li>
<li>不要存在where标签</li>
</ul>
</blockquote>
<h3 id="12、缓存（了解即可）"><a href="#12、缓存（了解即可）" class="headerlink" title="12、缓存（了解即可）"></a>12、缓存（了解即可）</h3><h4 id="12-1-简介"><a href="#12-1-简介" class="headerlink" title="12.1 简介"></a>12.1 简介</h4><h5 id="1-什么是缓存-Cache-？"><a href="#1-什么是缓存-Cache-？" class="headerlink" title="1. 什么是缓存[Cache]？"></a>1. 什么是缓存[Cache]？</h5><ul>
<li>存在内存中的临时数据。</li>
<li>将用户经常查询的数据放在缓存（内存）中，用户去查询数据就不用从磁盘上（关系型数据库查询文件）查询，从缓存中查询，从而提高查询效率，解决了高并发系统的性能问题。</li>
</ul>
<h5 id="2-为什么使用缓存？"><a href="#2-为什么使用缓存？" class="headerlink" title="2. 为什么使用缓存？"></a>2. 为什么使用缓存？</h5><ul>
<li>减少和数据库的交互次数，减少系统开销，提高系统效率。</li>
</ul>
<h5 id="3-什么样的数据能使用缓存？"><a href="#3-什么样的数据能使用缓存？" class="headerlink" title="3. 什么样的数据能使用缓存？"></a>3. 什么样的数据能使用缓存？</h5><ul>
<li>经常查询并且不经常改变的数据。【可以使用缓存】</li>
</ul>
<h4 id="12-2-Mybatis缓存"><a href="#12-2-Mybatis缓存" class="headerlink" title="12.2 Mybatis缓存"></a>12.2 Mybatis缓存</h4><ul>
<li><p>Mybatis包含一个非常强大的查询缓存特性，它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。</p>
</li>
<li><p>Mybatis系统中默认定义了两级缓存：</p>
<p>一级缓存</p>
<p>和</p>
<p>二级缓存</p>
<ul>
<li>默认情况下，只有一级缓存开启。（SqlSession级别的缓存，也称为本地缓存）</li>
<li>二级缓存需要手动开启和配置，它是基于namespace级别的缓存。</li>
<li>为了提高扩展性，Mybatis定义了缓存接口Cache，我们可以通过实现Cache接口来自定义二级缓存。</li>
</ul>
</li>
</ul>
<h4 id="12-3-一级缓存"><a href="#12-3-一级缓存" class="headerlink" title="12.3 一级缓存"></a>12.3 一级缓存</h4><ul>
<li>一级缓存也叫本地缓存：<ul>
<li>与数据库同一次会话期间查询到的数据会放在本地缓存中。</li>
<li>以后如果需要获取相同的数据，直接从缓存中拿，没必要再去查询数据库</li>
</ul>
</li>
</ul>
<p>测试步骤：</p>
<ol>
<li>开启日志！</li>
<li>测试在一个Session中查询两次相同记录</li>
<li>查看日志输出<br><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946682.png" alt="在这里插入图片描述"></li>
</ol>
<p>缓存失效的情况：</p>
<ol>
<li>查询不同的东西；</li>
<li>增删改操作，可能会改变原来的数据，所以必定会刷新缓存！<br><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946775.png" alt="在这里插入图片描述"></li>
<li>查询不同的Mapper.xml</li>
<li>手动清理缓存！<br><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946866.png" alt="在这里插入图片描述"></li>
</ol>
<p>小结：一级缓存默认是开启的，只在一次SqlSession中有效，也就是拿到连接到关闭连接这个区间段！<br>一级缓存相当于一个Map。</p>
<h3 id="13-4-二级缓存"><a href="#13-4-二级缓存" class="headerlink" title="13.4 二级缓存"></a>13.4 二级缓存</h3><ul>
<li>二级缓存也叫全局缓存，一级缓存作用域太低了，所以诞生了二级缓存；</li>
<li>基于namespace级别的缓存，一个名称空间，对应一个二级缓存；</li>
<li>工作机制<ul>
<li>一个会话查询一条数据，这个数据就会被放在当前会话的一级缓存中；</li>
<li>如果当前会话关闭了，这个会话对应的一级缓存就没了；但是我们想要的是，会话关闭了，一级缓存中的数据被保存到二级缓存中；</li>
<li>新的会话查询信息，就可以从二级缓存中获取内容；</li>
<li>不同的mapper查出的数据就会放在自己对应的缓存（map）中；</li>
</ul>
</li>
</ul>
<p>步骤：</p>
<ol>
<li>在mybatis-config.xml开启全局缓存</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--显示的开启全局缓存--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">setting</span> <span class="attr">name</span>=<span class="string">&quot;cacheEnabled&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="2">
<li>在要使用二级缓存的Mapper中开启</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--在当前Mapper.xml中使用二级缓存--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">cache</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>也可以自定义参数</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--在当前Mapper.xml中使用二级缓存--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">cache</span></span></span><br><span class="line"><span class="tag">        <span class="attr">eviction</span>=<span class="string">&quot;FIFO&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">flushInterval</span>=<span class="string">&quot;60000&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">size</span>=<span class="string">&quot;512&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">readOnly</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="3">
<li><p>测试</p>
</li>
<li><p>问题：如果没有自定义参数，则会报错，我们需要将实体类序列化！</p>
</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Cause: java.io.NotSerializableException: com.kuang.pojo.User</span><br></pre></td></tr></table></figure>

<blockquote>
<p>小结：</p>
<ul>
<li>只要开启了二级缓存，在同一个Mapper下就有效；</li>
<li>所有的数据都会先放在一级缓存中；</li>
<li>只有当会话提交或者关闭的时候，才会提交到二级缓存中！</li>
</ul>
</blockquote>
<h4 id="12-5-缓存原理"><a href="#12-5-缓存原理" class="headerlink" title="12.5 缓存原理"></a>12.5 缓存原理</h4><p><img src="https://gitee.com/mihaoyou/pic-go/raw/master/img/202309120946986.png" alt="在这里插入图片描述"></p>
<h4 id="12-6-自定义缓存-ehcache（可以了解）"><a href="#12-6-自定义缓存-ehcache（可以了解）" class="headerlink" title="12.6 自定义缓存-ehcache（可以了解）"></a>12.6 自定义缓存-ehcache（可以了解）</h4><p>Ehcache是一种广泛使用的开源Java分布式缓存，主要面向通用缓存。</p>
<p>要在程序中使用ehcache，先要导包！</p>
<p>在mapper中指定使用我们的ehcache缓存实现！</p>
<p><strong>目前：Redis数据库来做缓存！K-V</strong></p>

  </div>
  <div id="copyright"><style>#easter-egg{border:0;padding:10px 0;position:relative}#easter-egg::before{font-family:"Font Awesome 5 Free";font-weight:900;content:"本文结束 \f1b0  感谢阅读";position:absolute;
padding:0 10px;
line-height:1px;
white-space:nowrap;
left:50%;
transform:translateX(-50%)}
</style><hr id="easter-egg"><blockquote style="padding:0">
    <p>作者: <a href="https://mihaoyou.gitee.io">
        <a1>云静</a1>
    </a></p>
    <p>版权声明: 本博客所有文章除特别声明外, 均采用 <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)"><a1>CC BY-NC-ND 4.0</a1></a> 许可协议, 转载请注明出处！</p></blockquote><hr></div>
</article>


    <div class="blog-post-comments">
        <div id="utterances_thread">
            <noscript>加载评论需要在浏览器启用 JavaScript 脚本支持。</noscript>
        </div>
    </div>


        
          <div id="footer-post-container">
  <div id="footer-post">

    <div id="nav-footer" style="display: none">
      <ul>
         
          <li><a href="/">首页</a></li>
         
          <li><a href="/about/">关于</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a href="/categories/">分类</a></li>
         
          <li><a href="/search/">搜索</a></li>
        
      </ul>
    </div>

    <div id="toc-footer" style="display: none">
      <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-Mybatis%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">1.Mybatis简介</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9D%E8%AF%86mybatis"><span class="toc-number">1.1.</span> <span class="toc-text">初识mybatis</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E6%8C%81%E4%B9%85%E5%B1%82%EF%BC%9F"><span class="toc-number">1.2.</span> <span class="toc-text">什么是持久层？</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8"><span class="toc-number">2.</span> <span class="toc-text">2.快速入门</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-1-%E5%AE%89%E8%A3%85mybatis%EF%BC%88%E9%85%8D%E7%BD%AE%E4%BA%8Epom-xml%E4%B8%8B%EF%BC%89"><span class="toc-number">2.1.</span> <span class="toc-text">2.1.安装mybatis（配置于pom.xml下）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-2-%E9%85%8D%E7%BD%AE%E6%A0%B8%E5%BF%83%E6%96%87%E4%BB%B6%EF%BC%88mybatis-config-xml%E6%94%BE%E7%BD%AEresource%E7%9B%AE%E5%BD%95%E4%B8%8B%EF%BC%89"><span class="toc-number">2.2.</span> <span class="toc-text">2.2.配置核心文件（mybatis-config.xml放置resource目录下）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-3-%E5%88%9B%E5%BB%BA%E5%B7%A5%E5%85%B7%E7%B1%BB%EF%BC%88%E5%88%9B%E5%BB%BA%E4%BA%8Eutils%E5%8C%85%E4%B8%8B%EF%BC%89"><span class="toc-number">2.3.</span> <span class="toc-text">2.3.创建工具类（创建于utils包下）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4-%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BD%93%E7%B1%BB%EF%BC%88%E5%9C%A8entities%E4%B8%8B%EF%BC%89"><span class="toc-number">2.4.</span> <span class="toc-text">2.4.创建实体类（在entities下）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-5-%E5%88%9B%E5%BB%BA%E6%8E%A5%E5%8F%A3%EF%BC%88%E5%9C%A8dao%E6%88%96%E8%80%85mapper%E5%B1%82%E4%B8%8B%EF%BC%89"><span class="toc-number">2.5.</span> <span class="toc-text">2.5.创建接口（在dao或者mapper层下）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-6-%E9%85%8D%E7%BD%AEStudentMapper-xml%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-number">2.6.</span> <span class="toc-text">2.6.配置StudentMapper.xml配置文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-7-%E7%BC%96%E5%86%99%E6%B5%8B%E8%AF%95%E7%B1%BB"><span class="toc-number">2.7.</span> <span class="toc-text">2.7.编写测试类</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E9%85%8D%E7%BD%AE%E8%A7%A3%E6%9E%90"><span class="toc-number">3.</span> <span class="toc-text">3.配置解析</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#3-1%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE%EF%BC%88environments%EF%BC%89"><span class="toc-number">3.1.</span> <span class="toc-text">3.1环境配置（environments）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-2-%E5%B1%9E%E6%80%A7%EF%BC%88properties%EF%BC%89"><span class="toc-number">3.2.</span> <span class="toc-text">3.2 属性（properties）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-3%E7%B1%BB%E5%9E%8B%E5%88%AB%E5%90%8D%EF%BC%88typeAliases%EF%BC%89"><span class="toc-number">3.3.</span> <span class="toc-text">3.3类型别名（typeAliases）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-4%E8%AE%BE%E7%BD%AE"><span class="toc-number">3.4.</span> <span class="toc-text">3.4设置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-5-%E5%85%B6%E4%BB%96%E9%85%8D%E7%BD%AE"><span class="toc-number">3.5.</span> <span class="toc-text">3.5 其他配置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-6-%E6%98%A0%E5%B0%84%E5%99%A8%EF%BC%88mappers%EF%BC%89"><span class="toc-number">3.6.</span> <span class="toc-text">3.6 映射器（mappers）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-7-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%92%8C%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-number">3.7.</span> <span class="toc-text">3.7 生命周期和作用域</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E8%A7%A3%E5%86%B3%E5%B1%9E%E6%80%A7%E5%90%8D%E5%92%8C%E5%AD%97%E6%AE%B5%E5%90%8D%E4%B8%8D%E4%B8%80%E8%87%B4%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">4.</span> <span class="toc-text">4、解决属性名和字段名不一致的问题</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#4-1-%E9%97%AE%E9%A2%98"><span class="toc-number">4.1.</span> <span class="toc-text">4.1 问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-2-resultMap"><span class="toc-number">4.2.</span> <span class="toc-text">4.2 resultMap</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81%E6%97%A5%E5%BF%97%EF%BC%882020-10-24%EF%BC%89"><span class="toc-number">5.</span> <span class="toc-text">5、日志（2020-10-24）</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#5-1-%E6%97%A5%E5%BF%97%E5%B7%A5%E5%8E%82"><span class="toc-number">5.1.</span> <span class="toc-text">5.1 日志工厂</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-2-Log4j"><span class="toc-number">5.2.</span> <span class="toc-text">6.2 Log4j</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6%E3%80%81%E5%88%86%E9%A1%B5"><span class="toc-number">6.</span> <span class="toc-text">6、分页</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#6-1-%E4%BD%BF%E7%94%A8Limit%E5%88%86%E9%A1%B5"><span class="toc-number">6.1.</span> <span class="toc-text">6.1 使用Limit分页</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-2-RowBounds%E5%88%86%E9%A1%B5"><span class="toc-number">6.2.</span> <span class="toc-text">6.2 RowBounds分页</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-3-%E5%88%86%E9%A1%B5%E6%8F%92%E4%BB%B6"><span class="toc-number">6.3.</span> <span class="toc-text">6.3 分页插件</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7%E3%80%81%E4%BD%BF%E7%94%A8%E6%B3%A8%E8%A7%A3%E5%BC%80%E5%8F%91"><span class="toc-number">7.</span> <span class="toc-text">7、使用注解开发</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#7-1-%E9%9D%A2%E5%90%91%E6%8E%A5%E5%8F%A3%E7%BC%96%E7%A8%8B"><span class="toc-number">7.1.</span> <span class="toc-text">7.1 面向接口编程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#7-2-%E4%BD%BF%E7%94%A8%E6%B3%A8%E8%A7%A3%E5%BC%80%E5%8F%91"><span class="toc-number">7.2.</span> <span class="toc-text">7.2 使用注解开发</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#7-3-CRUD"><span class="toc-number">7.3.</span> <span class="toc-text">7.3 CRUD</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8%E3%80%81Lombok%EF%BC%88%E5%81%B7%E6%87%92%E7%9A%84%E8%AF%9D%E5%8F%AF%E4%BB%A5%E4%BD%BF%E7%94%A8%EF%BC%89"><span class="toc-number">8.</span> <span class="toc-text">8、Lombok（偷懒的话可以使用）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9%E3%80%81%E5%A4%9A%E5%AF%B9%E4%B8%80%E5%A4%84%E7%90%86"><span class="toc-number">9.</span> <span class="toc-text">9、多对一处理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#9-1%E6%B5%8B%E8%AF%95%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA"><span class="toc-number">9.1.</span> <span class="toc-text">9.1测试环境搭建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#9-2-%E6%8C%89%E7%85%A7%E7%BB%93%E6%9E%9C%E5%B5%8C%E5%A5%97%E5%A4%84%E7%90%86"><span class="toc-number">9.2.</span> <span class="toc-text">9.2 按照结果嵌套处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#9-3%E6%8C%89%E7%85%A7%E6%9F%A5%E8%AF%A2%E5%B5%8C%E5%A5%97%E5%A4%84%E7%90%86"><span class="toc-number">9.3.</span> <span class="toc-text">9.3按照查询嵌套处理</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#10-%E3%80%81%E4%B8%80%E5%AF%B9%E5%A4%9A%E5%A4%84%E7%90%86"><span class="toc-number">10.</span> <span class="toc-text">10 、一对多处理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#10-1-%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA"><span class="toc-number">10.1.</span> <span class="toc-text">10.1 环境搭建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#10-2%E6%8C%89%E7%85%A7%E7%BB%93%E6%9E%9C%E5%B5%8C%E5%A5%97%E5%A4%84%E7%90%86"><span class="toc-number">10.2.</span> <span class="toc-text">10.2按照结果嵌套处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#10-3%E6%8C%89%E7%85%A7%E6%9F%A5%E8%AF%A2%E5%B5%8C%E5%A5%97%E5%A4%84%E7%90%86"><span class="toc-number">10.3.</span> <span class="toc-text">10.3按照查询嵌套处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#10-4%E5%B0%8F%E7%BB%93"><span class="toc-number">10.4.</span> <span class="toc-text">10.4小结</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#11%E3%80%81%E5%8A%A8%E6%80%81SQL"><span class="toc-number">11.</span> <span class="toc-text">11、动态SQL</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#11-1%E6%90%AD%E5%BB%BA%E7%8E%AF%E5%A2%83"><span class="toc-number">11.1.</span> <span class="toc-text">11.1搭建环境</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#IF"><span class="toc-number">12.</span> <span class="toc-text">IF</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#choose-when-otherwise"><span class="toc-number">12.1.</span> <span class="toc-text">choose (when, otherwise)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#trim-where-set"><span class="toc-number">12.2.</span> <span class="toc-text">trim (where, set)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Foreach"><span class="toc-number">12.3.</span> <span class="toc-text">Foreach</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#SQL%E7%89%87%E6%AE%B5"><span class="toc-number">12.4.</span> <span class="toc-text">SQL片段</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#12%E3%80%81%E7%BC%93%E5%AD%98%EF%BC%88%E4%BA%86%E8%A7%A3%E5%8D%B3%E5%8F%AF%EF%BC%89"><span class="toc-number">13.</span> <span class="toc-text">12、缓存（了解即可）</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#12-1-%E7%AE%80%E4%BB%8B"><span class="toc-number">13.1.</span> <span class="toc-text">12.1 简介</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AF%E7%BC%93%E5%AD%98-Cache-%EF%BC%9F"><span class="toc-number">13.1.1.</span> <span class="toc-text">1. 什么是缓存[Cache]？</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BD%BF%E7%94%A8%E7%BC%93%E5%AD%98%EF%BC%9F"><span class="toc-number">13.1.2.</span> <span class="toc-text">2. 为什么使用缓存？</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-%E4%BB%80%E4%B9%88%E6%A0%B7%E7%9A%84%E6%95%B0%E6%8D%AE%E8%83%BD%E4%BD%BF%E7%94%A8%E7%BC%93%E5%AD%98%EF%BC%9F"><span class="toc-number">13.1.3.</span> <span class="toc-text">3. 什么样的数据能使用缓存？</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#12-2-Mybatis%E7%BC%93%E5%AD%98"><span class="toc-number">13.2.</span> <span class="toc-text">12.2 Mybatis缓存</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#12-3-%E4%B8%80%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="toc-number">13.3.</span> <span class="toc-text">12.3 一级缓存</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#13-4-%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="toc-number">14.</span> <span class="toc-text">13.4 二级缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#12-5-%E7%BC%93%E5%AD%98%E5%8E%9F%E7%90%86"><span class="toc-number">14.1.</span> <span class="toc-text">12.5 缓存原理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#12-6-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BC%93%E5%AD%98-ehcache%EF%BC%88%E5%8F%AF%E4%BB%A5%E4%BA%86%E8%A7%A3%EF%BC%89"><span class="toc-number">14.2.</span> <span class="toc-text">12.6 自定义缓存-ehcache（可以了解）</span></a></li></ol></li></ol>
    </div>

    <div id="share-footer" style="display: none">
      <ul>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://mihaoyou.gitee.io/mybatis/"><i class="fab fa-facebook fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://mihaoyou.gitee.io/mybatis/&text=mybatis"><i class="fab fa-twitter fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://mihaoyou.gitee.io/mybatis/&title=mybatis"><i class="fab fa-linkedin fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://mihaoyou.gitee.io/mybatis/&is_video=false&description=mybatis"><i class="fab fa-pinterest fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=mybatis&body=Check out this article: https://mihaoyou.gitee.io/mybatis/"><i class="fas fa-envelope fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://mihaoyou.gitee.io/mybatis/&title=mybatis"><i class="fab fa-get-pocket fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://mihaoyou.gitee.io/mybatis/&title=mybatis"><i class="fab fa-reddit fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://mihaoyou.gitee.io/mybatis/&title=mybatis"><i class="fab fa-stumbleupon fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://mihaoyou.gitee.io/mybatis/&title=mybatis"><i class="fab fa-digg fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://mihaoyou.gitee.io/mybatis/&name=mybatis&description="><i class="fab fa-tumblr fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://mihaoyou.gitee.io/mybatis/&t=mybatis"><i class="fab fa-hacker-news fa-lg" aria-hidden="true"></i></a></li>
</ul>

    </div>

    <div id="actions-footer">
        <a id="menu" class="icon" href="#" onclick="$('#nav-footer').toggle();return false;"><i class="fas fa-bars fa-lg" aria-hidden="true"></i> 菜单</a>
        <a id="toc" class="icon" href="#" onclick="$('#toc-footer').toggle();return false;"><i class="fas fa-list fa-lg" aria-hidden="true"></i> 目录</a>
        <a id="share" class="icon" href="#" onclick="$('#share-footer').toggle();return false;"><i class="fas fa-share-alt fa-lg" aria-hidden="true"></i> 分享</a>
        <a id="top" style="display:none" class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up fa-lg" aria-hidden="true"></i> 返回顶部</a>
    </div>

  </div>
</div>

        
        <footer id="footer">
      <div class="footer-left">
        Copyright &copy;
        
        
        2022-2023
        云雪
      </div>
      <div class="footer-right">
        <nav>
          <ul>
            <!--
          --><li><a href="/">首页</a></li><!--
        --><!--
          --><li><a href="/about/">关于</a></li><!--
        --><!--
          --><li><a href="/archives/">归档</a></li><!--
        --><!--
          --><li><a href="/categories/">分类</a></li><!--
        --><!--
          --><li><a href="/search/">搜索</a></li><!--
        -->
          </ul>
          <ul>
          
              <!-- 不蒜子统计 -->
              <span id="busuanzi_container_site_pv">
                  本站总访问量<span id="busuanzi_value_site_pv"></span>次
              </span>
              <span class="post-meta-divider">|</span>
              <span id="busuanzi_container_site_uv" style='display:none'>
                      本站访客数<span id="busuanzi_value_site_uv"></span>人
              </span>
            <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
            
          </ul>
        </nav>
      </div>
      
</footer>


    </div>
    <!-- styles -->



  <link rel="preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" crossorigin="anonymous" onload="this.onload=null;this.rel='stylesheet'"/>


    <!-- jquery -->
 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" crossorigin="anonymous"></script> 




<!-- clipboard -->

  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.7/clipboard.min.js" crossorigin="anonymous"></script> 
  
  <script type="text/javascript">
  $(function() {
    // copy-btn HTML
    var btn = "<span class=\"btn-copy tooltipped tooltipped-sw\" aria-label=\"复制到粘贴板！\">";
    btn += '<i class="far fa-clone"></i>';
    btn += '</span>'; 
    // mount it!
    $(".highlight table").before(btn);
    var clip = new ClipboardJS('.btn-copy', {
      text: function(trigger) {
        return Array.from(trigger.nextElementSibling.querySelectorAll('.code')).reduce((str,it)=>str+it.innerText+'\n','')
      }
    });
    clip.on('success', function(e) {
      e.trigger.setAttribute('aria-label', "复制成功！");
      e.clearSelection();
    })
  })
  </script>


<script src="/js/main.js"></script>

<!-- search -->

<!-- Google Analytics -->

<!-- Baidu Analytics -->

  <script type="text/javascript">
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?d052d72734717a430b46e4d07257350b";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
        </script>

<!-- Cloudflare Analytics -->

<!-- Umami Analytics -->

<!-- Disqus Comments -->

<!-- utterances Comments -->

    <script type="text/javascript">
      var utterances_repo = 'mihaoyou/huayu';
      var utterances_issue_term = 'pathname';
      var utterances_label = 'Comment';
      var utterances_theme = 'github-dark';

      (function(){
          var script = document.createElement('script');

          script.src = 'https://utteranc.es/client.js';
          script.setAttribute('repo', utterances_repo);
          script.setAttribute('issue-term', 'pathname');
          script.setAttribute('label', utterances_label);
          script.setAttribute('theme', utterances_theme);
          script.setAttribute('crossorigin', 'anonymous');
          script.async = true;
          (document.getElementById('utterances_thread')).appendChild(script);
      }());
  </script>

</body>
</html>
